package com.vectorimage.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("unchecked")
public class Tool{

	/**
	 * 设置cookie
	 */
	public static void setCookie(HttpServletResponse response, String key, String value, int time, String uri){
		try{
			Cookie c = new Cookie(key, java.net.URLEncoder.encode(value, "utf-8"));
			c.setMaxAge(time);
			if(uri != null){
				c.setPath(uri);
			}
			response.addCookie(c);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 过滤恶意HTML标签 参考网上：2011-01-03
	 */
	public static String filterHTML(String inputString){
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try{
			/* & —— &amp; */
			p_html = Pattern.compile("\\&", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&amp;");
			/* < —— &lt; */
			p_html = Pattern.compile("\\<", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&lt;");
			/* > —— &gt; */
			p_html = Pattern.compile("\\>", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&gt;");
			/* 空格 —— &nbsp; */
			p_html = Pattern.compile("\\ ", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&nbsp;");
			/* \n —— <br/> */
			// p_html = Pattern.compile("\\\n", Pattern.CASE_INSENSITIVE);
			// m_html = p_html.matcher(inputString);
			// inputString = m_html.replaceAll("<br/>");
		}catch(Exception e){
			e.printStackTrace();
		}
		return inputString;
	}

	/**
	 * 空格 &nbsp;转换 参考网上：2011-12-29
	 */
	public static String filterTheSpace(String inputString){
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try{
			/* & —— &amp; */
			p_html = Pattern.compile("\\&", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&amp;");
		}catch(Exception e){
			e.printStackTrace();
		}
		return inputString;
	}

	/**
	 * 解决Kindeditor修改功能漏洞 参考网上：2011-01-03
	 */
	public static String filterTheTag(String inputString){
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try{
			/* & —— &amp; */
			p_html = Pattern.compile("\\&", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&amp;");
			/* < —— &lt; */
			p_html = Pattern.compile("\\<", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&lt;");
			/* > —— &gt; */
			p_html = Pattern.compile("\\>", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll("&gt;");
		}catch(Exception e){
			e.printStackTrace();
		}
		return inputString;
	}

	/**
	 * 过滤非法sql字符 参考网上：2011-1-03
	 */
	public static String filterSQL(String inputString){
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try{
			/* ' —— （单引号——空格） */
			p_html = Pattern.compile("\\'", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll(" ");
			/* ; —— （分号——空格） */
			p_html = Pattern.compile("\\;", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll(" ");
			/* 1=1 —— （1=1——空格） */
			p_html = Pattern.compile("\\1=1", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll(" ");
			/* | —— （或者符合——空格） */
			p_html = Pattern.compile("\\|", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll(" ");
			/* < —— （<——空格） */
			p_html = Pattern.compile("\\<", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll(" ");
			/* > —— （>——空格） */
			p_html = Pattern.compile("\\>", Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(inputString);
			inputString = m_html.replaceAll(" ");
		}catch(Exception e){
			e.printStackTrace();
		}
		return inputString;
	}

	/**
	 * 获取客户端IP地址
	 */
	public static String getIP(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		System.out.println(ip);
		if(!checkIP(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(!checkIP(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(!checkIP(ip)){
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	private static boolean checkIP(String ip){
		if(ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip) || ip.split(".").length != 4){
			return false;
		}
		return true;
	}

	/**
	 * 根据IP地址获取地理位置，如：北京市
	 */
	public static String getAddressByIP(String ip){
		String ipAddress = ip;
		try{
			URL url = new URL("http://www.ip138.com/ips138.asp?ip=" + ip);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
			String line = null;
			StringBuffer result = new StringBuffer();
			while((line = reader.readLine()) != null){
				result.append(line);
			}
			reader.close();
			ip = result.substring(result.indexOf("主数据：") + 4, result.indexOf("</li><li>参考数据"));
			char[] ipStr = ip.toCharArray();
			for(int i = 0; i < ipStr.length; i++){
				if(i != 0 && !Character.isLetter(ipStr[i])){ // 判断是否汉字，不含中文特殊符号
					ip = ip.substring(0, i);
					break;
				}
			}
		}catch(StringIndexOutOfBoundsException indexOut){
			Logger log = Logger.getLogger(Tool.class);
			log.info("IP地址获取失败：下标越界\t" + ipAddress);
			return ipAddress;
		}catch(IOException e){
			return ipAddress;
		}
		return ip;
	}

	/**
	 * 判断恶意刷新点击量 true——第一次打开 false——非第一次
	 * 
	 * @param request
	 * @param articleId
	 * @return
	 */
	public static boolean isFirstVisit(HttpServletRequest request, String articleId){
		boolean isFirst = false;
		int markArticleId = 1;
		List<String> list = (List<String>)request.getSession().getAttribute("articleId");
		if(list == null){
			list = new ArrayList<String>();
			list.add(articleId);
			isFirst = true;
		}else{
			for(int i = 0; i < list.size(); i++){
				if(articleId.equals(list.get(i))){
					markArticleId = 2;
					break;
				}
			}
			// 不是同一文章点击数增加1
			if(markArticleId != 2){
				list.add(articleId);
				isFirst = true;
			}
		}
		request.getSession().setAttribute("articleId", list);
		return isFirst;
	}

	// 是否数字
	public static boolean isNumberic(String str){
		if(str == null) return false;
		for(int i = str.length(); --i >= 0;){
			if( !Character.isDigit(str.charAt(i))){
				return false;
			}
		}
		return true;
	}

	// 是否邮箱地址
	public static boolean isEmail(String email){
		if(email == null) return false;
		Pattern pattern = Pattern.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		Matcher matcher = pattern.matcher(email);
		if(matcher.find()){
			return true;
		}else{
			return false;
		}
	}

	// 是否时间，格式：yyyy-MM-dd（搜索围脖）
	public static boolean isTime(String time){
		try{
			if(time == null) return false;
			SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
			formater.parse(time);
			return true;
		}catch(Exception e){
			return false;
		}
	}

	/**
	 * 文章附件存储路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getFileUrl(HttpServletRequest request){
		String savePath = request.getSession().getServletContext().getRealPath("../FileData/attachs");
		File f1 = new File(savePath);
		if( !f1.exists()){
			f1.mkdirs();
		}
		return savePath;
	}

	/**
	 * 压缩图片文件
	 * 
	 * @param oldFile 要进行压缩的文件全路径
	 * @param newFile 图片输出路径
	 * @param width 宽度
	 * @param height 高度
	 * @param quality 质量
	 * @param smallIcon 小图片的后缀
	 * @return 返回压缩后的文件的全路径
	 */
	public static String zipImage(String oldFile, String newFile, int width, int height, float quality, String smallIcon){
		try{
			if(oldFile == null){
				return null;
			}
			/** 对服务器上的临时文件进行处理 */
			Image srcFile = ImageIO.read(new File(oldFile));
			/** 宽,高设定 */
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
			/** 源文件名，不含扩展名 */
			String newImageName = oldFile.substring(oldFile.lastIndexOf(File.separator) + 1, oldFile.lastIndexOf('.')) + smallIcon;
			/** 扩展名 */
			String extName = oldFile.substring(oldFile.lastIndexOf('.') + 1, oldFile.length());
			/** 新文件名，含路径 */
			newFile = newFile + newImageName + "." + extName;
			/** 压缩之后存放位置 */
			FileOutputStream out = new FileOutputStream(newFile);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
			/** 压缩质量 */
			jep.setQuality(quality, true);
			encoder.encode(tag, jep);
			out.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		return newFile;
	}

}